package com.xh.bussiness.xkw.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Base64;

/**
 * @author lwz
 * @description http发送https请求工具类
 */
@Component
public class XkwHttpsUtils {
	private static final Logger logger = LoggerFactory.getLogger(XkwHttpsUtils.class);


    private static String appApiId;

    private static String appApiSecret;

    @Value("${xkw.appId}")
    public void setAppId(String appApiId) {
        XkwHttpsUtils.appApiId = appApiId;
    }

    @Value("${xkw.secret}")
    public void setAppSecret(String appApiSecret) {
        XkwHttpsUtils.appApiSecret = appApiSecret;
    }

    /**
	 *  xkwOath认证接口调用方法
	 */
	public static String httpPost(String localUrl) throws Exception{
        URL url = new URL(localUrl);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        X509TrustManager xtm = getInstance();
        TrustManager[] tm = { xtm };
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, tm, null);
        con.setSSLSocketFactory(ctx.getSocketFactory());
        con.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        }); 
        int resCode;
        try {
        	resCode=con.getResponseCode();
		} catch (Exception e) {
			logger.error(e.toString());
        	throw new Exception("学科网DNS解析失败，未找到服务地址");
        }
        //服务服务地址可以联通，会返回相应的code码
        if(resCode==200){
        	InputStreamReader inputStreamReader = new InputStreamReader(con.getInputStream());
        	//读取服务器的响应内容并显示
        	String result="";
        	int respInt = inputStreamReader.read();
        	while( respInt != -1){
        		result+=(char)respInt;
        		respInt=inputStreamReader.read();
        	}
        	return result;
        }else{
        	throw new Exception("学科网服务地址无响应,异常码："+con.getResponseCode());
        }
	}

	/**
     * @author: lwz
     * @description: 获取 X509TrustManager 实例
     * @param: []
     * @return: javax.net.ssl.X509TrustManager
     * @date: 11:38 2018/1/11
     */
	private static X509TrustManager getInstance(){
	    return new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                // TODO Auto-generated method stub
                return null;
            }
            public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                    throws CertificateException {
                // TODO Auto-generated method stub

            }
            public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                    throws CertificateException {
                // TODO Auto-generated method stub

            }
        };
    }

    /**
     * 学科网api  http get
     * @param httpurl
     * @return
     */
    public static String doGet(String httpurl) {

        String encodeAuth = encodeAuth();

        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null;// 返回结果字符串
        try {
            // 创建远程url连接对象
            URL url = new URL(httpurl);
            // 通过远程url连接对象打开一个连接，强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();

            connection.setRequestProperty("Authorization", "Basic " + encodeAuth);
            // 设置连接方式：get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取远程返回的数据时间：60000毫秒
            connection.setReadTimeout(60000);
            // 发送请求
            connection.connect();
            // 通过connection连接，获取输入流
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                // 封装输入流is，并指定字符集
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                // 存放数据
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }else{
                is = connection.getInputStream();
                // 封装输入流is，并指定字符集
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                // 存放数据
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            connection.disconnect();// 关闭远程连接
        }

        return result;
    }

    /**
     *
     *  学科网api  http post
     * @param url
     * @param jsonObject object
     * @return json object
     */
    public static String doPost(String url, JSONObject jsonObject) {
        String encodeAuth = encodeAuth();
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        JSONObject response = null;

        post.setHeader("Authorization", "Basic " + encodeAuth);
        try {
            StringEntity s = new StringEntity(jsonObject.toString());
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");
            post.setEntity(s);
            HttpResponse res = client.execute(post);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = res.getEntity();
                String result = EntityUtils.toString(entity);
                return result;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    private static String encodeAuth() {
        String auth = appApiId + ":" + appApiSecret;
        String encodeAuth = Base64.getUrlEncoder().encodeToString(auth.getBytes());
        return encodeAuth;
    }
}